<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="mini">
      <el-row :gutter="15">
        <div class="orderNo">退换货单号：{{ form.saleReturnOdd }}</div>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="选择销售单" prop="saleOdd">
            <el-input v-model="form.saleOdd" :readonly="isReadOnly" class="input-with-select">
              <el-button slot="append" :disabled="isReadOnly" @click="isSaleOpen = true">选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="仓库" prop="wareId">
            <treeselect v-model="form.wareId" :disabled="isReadOnly" :normalizer="normalizer" :options="wareOptions" placeholder="请选择"
                        @select="handleTreeSelectNode"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="销售人" prop="salePersonName">
            <el-input v-model="form.salePersonName" :disabled="true" placeholder="请输入"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系电话">
            <el-input v-model="form.phonenumber" :disabled="true" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">销售商品</el-divider>
      <el-row>
        <el-table v-loading="loading" :data="form.saleDetailsList" border>
          <el-table-column align="center" label="商品编号" prop="commodityNo"/>
          <el-table-column align="center" label="商品名称" prop="commodityName1"/>
          <el-table-column align="center" label="商品类别" prop="commodityType"/>
          <el-table-column align="center" label="规格" prop="commoditySpec"/>
          <el-table-column align="center" label="单位" prop="unitName1"/>
          <el-table-column align="center" label="单位关系" prop="unitRelationship"/>
          <el-table-column align="center" label="换算结果" prop="unitResult"/>
          <el-table-column align="center" label="成本总价" prop="costPrice">
            <template slot-scope="scope">
              <span>{{ formattedNumber(scope.row.unitResult * scope.row.costPrice) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="销售单价" prop="salePrice">
            <template slot-scope="scope">
              <span>{{ formattedNumber(scope.row.salePrice) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="销售数量" prop="saleNumber"/>
          <el-table-column align="center" label="退换方式" prop="returnType">
            <template slot-scope="scope">
              <el-select v-model="scope.row.returnType" placeholder="请选择">
                <el-option v-for="item in returnTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="退货数量" prop="commodityNumber">
            <template slot-scope="scope">
              <el-input v-model="scope.row.commodityNumber" onkeyup="this.value = this.value.replace(/[^A-z0-9]/, '')" type="number" @input="calculateSubTotal(scope.row.commodityNumber, scope.row, 'commodityNumber')"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
            <template slot-scope="scope">
              <el-button icon="el-icon-delete" size="mini" type="text" @click="handleDeleteSaleDetails(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-divider content-position="left">退换商品
        <el-button v-if="!isReadOnly" :disabled="!form.wareId" icon="el-icon-plus" plain size="mini" style="margin-left: 20px;" type="primary" @click="handleAddCommodity">添加商品</el-button>
      </el-divider>
      <el-row>
        <el-table v-loading="loading" :data="form.saleReturnDetailsList" border>
          <el-table-column align="center" label="商品编号" prop="commodityNo"/>
          <el-table-column align="center" label="商品名称" prop="commodityName1"/>
          <el-table-column align="center" label="商品类别" prop="commodityType"/>
          <el-table-column align="center" label="规格" prop="commoditySpec"/>
          <el-table-column align="center" label="单位" prop="unitName1">
            <template slot-scope="scope">
              <el-select v-model="scope.row.commodityUnitId" placeholder="请选择" @change="handleTableRowSelectChange($event, scope.row)">
                <el-option v-for="item in scope.row.unitList" :key="item.commodityUnitId" :label="item.unitName1" :value="item.commodityUnitId"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="单位关系" prop="unitRelationship"/>
          <el-table-column align="center" label="换算结果" prop="unitResult"/>
          <el-table-column align="center" label="库存数量" prop="numberList">
            <template slot-scope="scope">
              <span>{{ numberSum(scope.row.numberList) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="成本价" prop="costPrice">
            <template slot-scope="scope">
              <span>{{ formattedNumber( scope.row.costPrice) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="退换数量" prop="commodityNumber">
            <template slot-scope="scope">
              <el-input v-model="scope.row.commodityNumber" type="number" onkeyup="this.value = this.value.replace(/[^A-z0-9]/, '')" @input="calcNumber(scope.row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="销售单价" prop="salePrice" width="150px;">
            <template slot-scope="scope">
              <el-input v-model="scope.row.salePrice" type="number" @input="calculateSubTotal(scope.row.salePrice, scope.row, 'salePrice')"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="小计" prop="subtotal" width="150px;">
            <template slot-scope="scope">
              {{ formattedNumber(calculateSubTotal(scope.row.subtotal, scope.row, 'subtotal')) }}
            </template>
          </el-table-column>
          <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
            <template slot-scope="scope">
              <el-button icon="el-icon-delete" size="mini" type="text" @click="handleDeleteSaleReturnDetails(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row :gutter="15" style="margin-top: 40px">
        <el-col :span="5">
          <el-form-item label="销售运费" prop="logisticsCost">
            <el-input v-model="form.logisticsCost" class="input-with-select" placeholder="请输入" type="number">
              <el-select slot="prepend" v-model="form.logisticsMethod" placeholder="请选择" style="width: 110px;">
                <el-option v-for="item in methodOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="其他费用" prop="otherCost">
            <el-input v-model="form.otherCost" class="input-with-select" placeholder="请输入" type="number">
              <el-select slot="prepend" v-model="form.otherMethod" placeholder="请选择" style="width: 110px;">
                <el-option v-for="item in methodOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="付款方式" prop="payType">
            <el-select v-model="form.payType" placeholder="请选择">
              <el-option v-for="item in payTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <div class="pay-amount-div">退货总额：<span class="">{{ formattedNumber(form.returnPrice) }}</span></div>
      <el-row>
        <el-col :span="24">
          <el-form-item label="单据备注" prop="remark">
            <el-input v-model="form.remark" :rows="4" placeholder="请输入单据备注" type="textarea"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer-options">
      <el-button type="primary" @click="submitForm()">提交审核</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <!-- 选择销售单 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isSaleOpen" append-to-body title="选择销售单" width="800px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="销售单号" prop="saleOdd">
          <el-input v-model="queryParams.saleOdd" placeholder="请输入销售单号" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table  v-loading="loading" :data="ErpSaleList" @selection-change="handleSelectionChange" border>
        <el-table-column align="center" label="客户" prop="customerName" width="250px;"/>
        <el-table-column align="center" label="销售单号" prop="saleOdd" width="200px;"/>
        <el-table-column align="center" label="销售人" prop="nickName"/>
        <el-table-column align="center" label="销售金额" prop="payAmount"/>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleSaleChange(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="saleTotal > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="saleTotal"  @pagination="handleGetListSale"/>
    </el-dialog>

    <!-- 选择商品 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isCommodityOpen" append-to-body title="选择商品" width="80%">
      <ErpCommodity v-if="isCommodityOpen" :notCommodityIds="notCommodityIds" :wareId="wareId" @SelectionChange="handleSelectionChange"></ErpCommodity>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSelectedCommdity">确 定</el-button>
        <el-button @click="isCommodityOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {getErpSale, listErpSale} from "@/api/erp/ErpSale";
import {addErpSaleReturn, getErpSaleReturn, updateErpSaleReturn} from "@/api/erp/ErpSaleReturn";
import {listErpWareHouse} from "@/api/erp/ErpWareHouse";
import ErpCommodity from '@/views/erp/ErpCommodity/selectedCommodity'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {formattedNumber} from "@/utils/ruoyi";

export default {
  components: {
    ErpCommodity,
    Treeselect
  },
  props: [],
  dicts: ['erp_procure_batch', 'erp_logistics_stauts'],
  data() {
    return {
      // 分摊方式
      methodOptions: [
        {
          value: 1,
          label: '按重量分摊'
        }, {
          value: 2,
          label: '按体积分摊'
        }
      ],
      // 退货类型
      returnTypeOptions: [
        {
          value: 1,
          label: '退货'
        }, {
          value: 2,
          label: '退换'
        }
      ],
      // 收付款方式
      payTypeOptions: [
        {
          value: 1,
          label: '现金'
        }, {
          value: 2,
          label: '微信'
        }, {
          value: 3,
          label: '支付宝'
        }, {
          value: 4,
          label: '银行转账'
        }
      ],
      // 商品table loading
      loading: true,
      // 销售单列表
      ErpSaleList: [],
      // 显示搜索条件
      showSearch: true,
      // 总记录条数
      saleTotal: 0,
      // 销售单弹框
      isSaleOpen: false,
      // 临时存放
      temporyList: [],
      // 选择商品弹框
      isCommodityOpen: false,
      // 仓库
      wareOptions: [],
      // 选中仓库id
      wareId: null,
      // 商品过滤
      notCommodityIds: [],
      // 是否只读
      isReadOnly: false,
      form: {
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        saleStatus: 2,
        saleOdd:null,
      },
      rules: {
        saleOdd: [
          {required: true, message: "请选择销售单", trigger: "blur"}
        ],
      },
    }
  },
  computed: {
    calculateSubtotal() {
      //销售商品
      let subtotalSum = 0;
      this.form.saleDetailsList.forEach(item => {
        subtotalSum += (!item.commodityNumber ? 0 : item.commodityNumber) * item.salePrice;
      })
      //退换商品
      let subtotalSum2 = 0;
      this.form.saleReturnDetailsList.forEach(item => {
        subtotalSum2 += (!item.commodityNumber ? 0 : item.commodityNumber) * item.salePrice;
      })
      return parseFloat(!this.form.logisticsCost ? 0 : this.form.logisticsCost) + parseFloat(!this.form.otherCost ? 0 : this.form.otherCost) + subtotalSum - subtotalSum2;
    },
  },
  watch: {
    'form.saleDetailsList.subtotal': {
      handler(newVal) {
        this.form.returnPrice = this.calculateSubtotal
      },
      deep: true
    },
    'form.logisticsCost': {
      handler(newVal) {
        this.form.returnPrice = this.calculateSubtotal
      },
      deep: true
    },
    'form.otherCost': {
      handler(newVal) {
        this.form.returnPrice = this.calculateSubtotal
      },
      deep: true
    },
  },
  created() {
    this.reset();
    this.handleGetListSale();
    this.getTreeselect();
    const saleReturnId = this.$route.params && this.$route.params.saleReturnId;
    if (saleReturnId != 0) {
      this.isReadOnly = true;
      this.getSaleReturnInfo(saleReturnId);
    } else {
      this.loading = false;
    }
  },
  methods: {
    formattedNumber,
    // 获取销售单列表
    handleGetListSale() {
      this.loading = true;
      listErpSale(this.queryParams).then(response => {
        this.ErpSaleList = response.rows;
        this.saleTotal = response.total;
        this.loading = false;
      })
    },
    getSaleReturnInfo(saleId) {
      this.loading = true;
      getErpSaleReturn(saleId).then(response => {
        this.form = response.data;
        this.form.saleDetailsList = [];
        this.form.saleReturnDetailsList = [];
        response.data.detailsList.forEach(item => {
          if (item.returnCommodityType == 1) {
            this.form.saleDetailsList.push(item);
          } else {
            this.form.saleReturnDetailsList.push(item);
          }
        })
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.handleGetListSale();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 转换仓库管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.wareId,
        label: node.wareName,
        children: node.children
      };
    },
    /** 查询仓库管理下拉树结构 */
    getTreeselect() {
      listErpWareHouse().then(response => {
        this.wareOptions = this.handleTree(response.data, "wareId", "warePid");
      });
    },
    // 表单重置
    reset() {
      this.form = {
        saleReturnId: null,
        saleReturnOdd: 'XST' + this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}'),
        saleId: null,
        saleOdd: null,
        wareId: null,
        returnStatus: null,
        returnPrice: null,
        remark: null,
        logisticsCost: null,
        logisticsMethod: 1,
        otherCost: null,
        otherMethod: 1,
        subtotal:0,
        paymentMethod: null,
        createId: null,
        createName: null,
        createTime: null,
        flag: null,
        approveStatus: null,
        approveId: null,
        approveName: null,
        approveTime: null,
        rejectTime: null,
        rejectReason: null,
        detailsList: [],
        saleDetailsList: [],
        saleReturnDetailsList: []
      };
      this.resetForm("form");
    },
    // 商品单位选择
    handleTableRowSelectChange(e, row) {
      let obj = row.unitList.find(item => {
        return item.commodityUnitId == e
      })
      row.unitRelationship = obj.unitRelationship;
      row.unitResult = obj.unitResult;
      row.costPrice = obj.unitResult * obj.costPrice;
    },
    // 销售单选择
    handleSaleChange(row) {
      this.form.saleOdd = row.saleOdd;
      this.form.saleId = row.saleId;
      this.form.salePersonName = row.nickName;
      this.form.phonenumber = row.phonenumber;
      this.form.saleDetailsList = [];
      this.form.saleReturnDetailsList = [];
      // 根据所选择的销售单加载对应商品
      getErpSale(row.saleId).then(res => {
        res.data.detailsList.forEach(item => {
          this.form.saleDetailsList.push({
            ...item,
            orderOdd: this.form.saleReturnOdd,
            orderType: 2,
            returnCommodityType: 1,
            returnType: 1,
          })
        })
        this.isSaleOpen = false;
        // 重新计算退货总额
        this.calculateSubTotal();
      })
    },
    // 仓库选择
    handleTreeSelectNode(e) {
      this.wareId = e.wareId;
    },
    // 选择商品
    handleAddCommodity() {
      // 设置商品过滤id
      //this.notCommodityIds = this.form.saleDetailsList.map(item => item.commodityId);
      //this.notCommodityIds = this.notCommodityIds.concat(this.form.saleReturnDetailsList.map(item => item.commodityId));
      this.isCommodityOpen = true;
      // 重新计算退货总额
      this.calculateSubTotal();
    },
    // 提交数据
    submitForm(type) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.detailsList = this.form.saleDetailsList.concat(this.form.saleReturnDetailsList)
          if (this.form.saleReturnId != null) {
            updateErpSaleReturn(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              const obj = {path: "/psi/outStock/ErpSaleReturn", name: "ErpSaleReturn"};
              this.$tab.closeOpenPage(obj);
              this.$tab.refreshPage(obj);
            });
          } else {
            addErpSaleReturn(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              const obj = {path: "/psi/outStock/ErpSaleReturn", name: "ErpSaleReturn"};
              this.$tab.closeOpenPage(obj);
              this.$tab.refreshPage(obj);
            });
          }
        }
      });
    },
    // 取消
    cancel() {
      const obj = {path: "/psi/outStock/ErpSaleReturn", name: "ErpSaleReturn"};
      this.$tab.closeOpenPage(obj);
      this.$tab.refreshPage(obj);
    },
    // 商品选择
    handleSelectionChange(selection) {
      this.temporyList = selection;
    },
    // 确定选择商品
    submitSelectedCommdity() {
      this.temporyList.forEach(item => {
        this.form.saleReturnDetailsList.push({
          ...item,
          orderOdd: this.form.saleReturnOdd,
          orderType: 2,
          returnCommodityType: 2,
          commodityNumber: 1,
          returnType: 2,
        })
      })
      this.isCommodityOpen = false;
    },
    /** 计算小计 */
    calculateSubTotal(v, row, field) {
      if (v) {
        row[field] = v;
      }
      if(row.commodityNumber > row.saleNumber){
        this.$modal.msgError("商品编号["+row.commodityNo+"]退换货数量不能大于销售数量!");
        row.commodityNumber = row.saleNumber;
      }
      if(row.commodityNumber < 1){
        this.$modal.msgError("商品编号["+row.commodityNo+"]退换货数量不能小于销售数量!");
        row.commodityNumber = 1;
      }
      row.subtotal = parseFloat(!row.commodityNumber ? 0 : row.commodityNumber) * parseFloat(!row.salePrice ? 0 : row.salePrice);
      this.form.payAmount = 0;
      //销售商品
      let subtotalSum = 0;
      this.form.saleDetailsList.forEach((item) => {
        subtotalSum += parseFloat(!item.subtotal ? 0 : item.subtotal);
      });
      //退换商品
      let subtotalSum2 = 0;
      this.form.saleReturnDetailsList.forEach((item) => {
        subtotalSum2 += parseFloat(!item.subtotal ? 0 : item.subtotal);
      });
      this.form.returnPrice = parseFloat(!this.form.logisticsCost ? 0 : this.form.logisticsCost) + parseFloat(!this.form.otherCost ? 0 : this.form.otherCost) + subtotalSum - subtotalSum2;
      return row[field];
    },
    // 销售商品 根据对象删除数组
    handleDeleteSaleDetails(row) {
      const index = this.form.saleDetailsList.indexOf(row);
      if (index > -1) {
        this.form.saleDetailsList.splice(index, 1);
      }
    },
    // 退换商品 根据对象删除数组
    handleDeleteSaleReturnDetails(row) {
      //退换商品
      let subtotalSum2 = 0;
      this.form.saleReturnDetailsList.forEach((item) => {
        subtotalSum2 += parseFloat(!item.subtotal ? 0 : item.subtotal);
      });
      const index = this.form.saleReturnDetailsList.indexOf(row);
      if (index > -1) {
        this.form.saleReturnDetailsList.splice(index, 1);
      }
      this.form.returnPrice += subtotalSum2;
    },
    /** 数值累计 */
    numberSum(list) {
      let sum = 0;
      list.forEach(i => {
        sum += i.commodityNumber;
      })
      return sum;
    },
    /** 数值限制 */
    calcNumber(row){
      if(row.commodityNumber < 1){
        this.$modal.msgError("商品编号["+row.commodityNo+"]退换数量不能小于1!");
        row.commodityNumber = 1
      }
    }
  }
}

</script>
<style></style>
